import React, {useEffect, useState, useRef} from 'react'
import {Button, Space, message, Popconfirm, Tag} from 'antd'

import type {ColumnsType} from 'antd/es/table'
import {history} from 'umi'
import Permissions from '@/components/Permissions'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import {getTableList, removeProcess} from '@/service/workflow/configure'
import {getDict} from '@/service/common/dict'
import {processConfigType} from '../dict'

const formItemLayout = {
	labelCol: {flex: '80px'},
	wrapperCol: {flex: '1'},
}

const contract = () => {
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [selectId, setSelectId] = useState('')
	const [loading, setLoading] = useState(false)
	const [dict, setDict] = useState({
		processStuta: [],
		Process_Type: [],
	})
	const [tableList, setTableList] = useState<any[]>([])
	const [total, setTotal] = useState(0)

	const [searchData, setSearchData] = useState({})
	const [formData, setFormData] = useState<any[]>([])

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getTableList({...params, ...searchData})
			.then((res: any) => {
				if (res?.data?.records) {
					setTableList(() => res?.data?.records)
					setTotal(res?.data?.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}

	useEffect(() => {
		getDict(
			{
				dictKeys: ['processStuta', 'Process_Type'],
			},
			(res: any) => {
				setDict(() => res)
			},
		)
	}, [])

	// 删除事件
	const onDeleteFun = (ids?: any) => {
		const sid: string = ids || selectId
		removeProcess(sid)
			.then((res) => {
				if (res?.success) {
					message.success(res.msg)
					onListFun()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	// 列表
	const columns: ColumnsType<contractAPI.ContractColumns> = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text, record, index) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},

		{
			title: '流程分类Value',
			dataIndex: 'processValue',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '流程分类Key',
			dataIndex: 'processKey',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => (
				<span>
					{text ? <Tag color="processing">{text}</Tag> : '--'}
				</span>
			),
		},
		{
			title: '参数类型',
			dataIndex: 'processConfigType',
			align: 'center',
			width: 150,
			render: (text: number) => (
				<>
					{processConfigType?.map((item: any) => {
						if (Number(item?.dictKey) === Number(text)) {
							return (
								<Tag color="processing">{item?.dictValue}</Tag>
							)
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '参数Key',
			dataIndex: 'processConfigKey',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '审核节点',
			dataIndex: 'auditNode',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => (
				<span>
					{text ? <Tag color="processing">{text}</Tag> : '--'}
				</span>
			),
		},
		{
			title: '参数名称',
			dataIndex: 'processConfigName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text, record: any) => (
				<div>
					<Permissions permissionID="amc_system_workflow_configure_view">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/workflow/configure/view',
									query: {
										id: record?.id,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_workflow_configure_edit">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/workflow/configure/edit',
									query: {
										id: record?.id,
									},
								})
							}}>
							编辑
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_workflow_configure_delete">
						<Popconfirm
							placement="topLeft"
							title="你确定要删除这条数据吗？"
							onConfirm={() => onDeleteFun(record.id)}
							okText="确定"
							cancelText="取消">
							<Button type="link" size="small">
								删除
							</Button>
						</Popconfirm>
					</Permissions>
				</div>
			),
		},
	]

	const onFinish = (values: any) => {
		setSearchData(values)
	}

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [searchData])
	// 获取表格数据
	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	// 搜索重置
	const onReset = () => {
		setSearchData({})
	}

	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'select',
						label: '流程分类',
						name: 'processKey',
						key: 'processKey',
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.Process_Type],
					},
					{},
					{},
				],
			},
		]
		setFormData(formItems)
	}, [dict])

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_system_workflow_configure_add">
						<Button
							type="primary"
							ghost
							size="small"
							onClick={() => {
								history.push('/workflow/configure/add')
							}}>
							新增
						</Button>
					</Permissions>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					params={params}
					kid="id"
					columns={columns}
					pagination
					total={total}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={tableList}
					selectCallback={(keys: any) => {
						setSelectId(() => keys?.join(','))
					}}
				/>
			</div>
		</div>
	)
}

export default contract
